<?php
namespace Api\Controller;
use Api\Common\Page;
use Think\Model;
use Common\Model\BookModel;

//接收请求，并返回
class ReceiveController extends BaseController {

    public $post;//提交的post值;token，type:事件类型，data：处理的数据；

    //验证AK、SK，给出token值
    public function register(){
        $post = I("post.");
        if(empty($post['AK'] || $post['SK'])){  //验证AK、SK是否都存在
            $data['status'] = 404;
            $data['error_msg'] = "请输入正确的验证信息！";
            $this->retJson($data);
        }
        $verify = M('verify')->where(['ak'=>$post['AK'],'sk'=>$post['SK']])->find();
        if(empty($verify)){                     //验证AK、SK是否正确
            $data['status'] = 404;
            $data['error_msg'] = "请输入正确的验证信息！";
            $this->retJson($data);
        }
        $save['token'] = substr(sha1(uniqid(mt_rand().time(),1)),10,10);
        $save['time'] = time()+2*60*60; //token有效期为2小时
        $ret = M('verify')->where(['verify_id'=>$verify['verify_id']])->save($save);    //存入token与期有效期（覆盖）
        if(!$ret){                  //如果生成token失败
            $data['status'] = 404;
            $data['error_msg'] = "获取token失败！";
            $this->retJson($data);
        }else{                      //成功，返回200、token
            $data['status'] = 200;
            $data['token'] = $save['token'];
            $this->retJson($data);
        }
    }

//        生成
//        $post_data["AK"] = substr(sha1(uniqid(mt_rand(),1)),6,32);
//        $post_data["SK"] = substr(sha1(uniqid(mt_rand(),1)),6,32);

    //验证token
    public function verify(){
        $this->post = I("post.");
        if(empty($this->post["token"])){   //验证是否有token值
            $data['status'] = 404;
            $data['error_msg'] = "没有Token值！";
            $this->retJson($data);
        }
        $r = M('verify')->where(['token'=>$this->post["token"]])->find();
        if(empty($r)){                      //验证token值是否正确
            $data['status'] = 404;
            $data['error_msg'] = "请提交正确的Token值！";
            $this->retJson($data);
        }
        if($r['time']<=time()){              //验证token值是否过期
            $data['status'] = 404;
            $data['error_msg'] = "Token已过期，请重新注册！";
            $this->retJson($data);
        }
        $this->distribute();
    }

    //进行事件分发
    private function distribute(){
        if(empty($this->post['type'])){
            $data['status'] = 404;
            $data['error_msg'] = "请提交事件类型！";
            $this->retJson($data);
        }
        switch ($this->post['type']){
            case "verify_token":
                $data['status'] = 200;
                $data['error_msg'] = "验证成功！";
                $this->retJson($data);
                break;
            case "one":
                $this->one();
                break;
            case "all":
                $this->all();
                break;
            default:
                $data['status'] = 404;
                $data['error_msg'] = "您提交的事件不存在！";
                $this->retJson($data);
        }
    }


    //只读取一条数据
    //data spbs 新华码
    private function one() {
        $post_data = json_decode(htmlspecialchars_decode($this->post['data']),true);

        $map['is_del'] = 0;
        if (empty($post_data['spbs'])) {
            $ret['status'] = 404;
            $ret['error_msg'] = "请指定spbs！";
        }else{
            $map['spbs'] = $post_data['spbs'];
            $m = M('Book');

            $ret['status'] = 200;
            $ret['data'] = $m->where($map)
                ->field($this->get_export_field())
                ->order('book_id desc')->select();
            foreach ($ret['data'] as $k => $v){
                $r = M("order_has_book")->where(array(["book_id"=>$v["book_id"],["type"=>1],["is_backed"=>0]]))
                    ->field("sum(quantity) as quantity,sum(num_backed) as num_backed,sum(num_broken) as num_broken")
                    ->group("book_id")
                    ->find();
                $ret['data'][$k]["num_loan"] = $r['quantity']-$r['num_backed']-$r['num_broken'];
                unset($ret['data'][$k]["book_id"]);
            }
        }

        $this->retJson($ret);
    }

    //读取所有数据
    private function all() {
        $post_data = json_decode(htmlspecialchars_decode($this->post['data']),true);
        $_GET['p'] = !empty($post_data['p'])?$post_data['p']:1;
        $map['is_del'] = 0;
        $m = M('Book');
        $count = $m->where($map)->count();// 查询满足要求的总记录数
        $Page = new  Page($count ,100);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $ret['status'] = 200;
        $ret['data'] = $m->where($map)
            ->field($this->get_export_field())
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->order('book_id desc')
            ->select();
        foreach ($ret['data'] as $k => $v){
            $r = M("order_has_book")->where(array(["book_id"=>$v["book_id"],["type"=>1],["is_backed"=>0]]))
                ->field("sum(quantity) as quantity,sum(num_backed) as num_backed,sum(num_broken) as num_broken")
                ->group("book_id")
                ->find();
            $ret['data'][$k]["num_loan"] = $r['quantity']-$r['num_backed']-$r['num_broken'];
            unset($ret['data'][$k]["book_id"]);
        }
        $this->retJson($ret);
    }

    //设置返回字段
    private function get_export_field(){
        return 'book_id,spbs,stock_rent,stock_buy';
    }

    public function retJson($data){
        echo json_encode($data);
        exit;
    }
}